﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Security;
namespace SP.OpenSource.CDC.Monitor.BLL
{
    class Crypt
    {
        static byte [] s_aditionalEntropy = { 9, 8, 7, 6, 5 };
        byte [] secret = { 0, 1, 2, 3, 4, 1, 2, 3, 4 };

        public static bool Encrypt(String sDataToEncrypt, String strDataProtectionType,ref String sOutEncryptedData,ref String sErrorMessage)
        {
            try
            {
                byte[] byteDataToEncry = UnicodeEncoding.Unicode.GetBytes(sDataToEncrypt);
                
                byte[] byteEncryptedData = null;
                if (strDataProtectionType == "USERKEY")
                    byteEncryptedData = ProtectedData.Protect(byteDataToEncry, s_aditionalEntropy, DataProtectionScope.CurrentUser);
                else
                    byteEncryptedData = ProtectedData.Protect(byteDataToEncry, s_aditionalEntropy, DataProtectionScope.LocalMachine);
                
                sOutEncryptedData = Convert.ToBase64String(byteEncryptedData, 0, byteEncryptedData.Length);
                
                sErrorMessage = String.Empty;
                return true;
            }
            catch (CryptographicException e)
            {
                sErrorMessage = e.Message;
                return false;
            }
        }
        
        public static bool Decrypt(String sInEncryptedData, String sDataProtectionType,ref String sOutDecryData, ref String sErrorMessage)
        {
            try
            {
                byte[] byteDecryptedData = null;

                char[] carray = sInEncryptedData.ToCharArray();
                byte[] byteEncryptedData = Convert.FromBase64CharArray(carray, 0, carray.Length);
                

                sErrorMessage = String.Empty; 
                if (null == byteEncryptedData)
                {
                    sErrorMessage = "An attempt to decrypt failed.";
                    return false;
                }
                if (sDataProtectionType == "USERKEY")
                    byteDecryptedData = ProtectedData.Unprotect(byteEncryptedData, s_aditionalEntropy, DataProtectionScope.CurrentUser);
                else
                    byteDecryptedData = ProtectedData.Unprotect(byteEncryptedData, s_aditionalEntropy, DataProtectionScope.LocalMachine);

                UnicodeEncoding aEnc = new UnicodeEncoding();
                sOutDecryData = aEnc.GetString(byteDecryptedData.ToArray());
              return true;
            }
            catch (CryptographicException e)
            {
                sErrorMessage = e.Message;
                return false;
            }
        }
    }
}
